package day6.Component;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;

public class TestCanvas2 extends JFrame{
	private Canvas can;
	public TestCanvas2(String title) {
	this.setTitle(title);
	this.setSize(400, 500);
	this.setLocationRelativeTo(null);
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	initComponent();
	
	// 放到最后显示窗口
	this.setVisible(true);
}
// 初始化
private void initComponent() {
//借助画布工具
	 can = new Canvas(){

		@Override
		public void paint(Graphics g) {
			g.setColor(Color.pink);
			g.drawLine(0, 0, can.getWidth(),can.getHeight());
		}
		
	};
	can.addMouseMotionListener(new MouseAdapter() {
           int lastX;
           int lastY;
           int currentX;
           int currentY;
           
		@Override
		public void mouseDragged(MouseEvent e) {
            lastX = currentX;
            lastY = currentY;
			currentX =(int) (Math.random()*can.getWidth());           
                currentY =(int) (Math.random()*can.getHeight());           
			Graphics g = can.getGraphics();
           
             
             g.drawLine(lastX, lastY, currentX, currentY);
		}
		
	});
	this.add(can);
}
public static void main(String[] args) {
	new TestCanvas2("画布");
}


}
